﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;


namespace DotNetNuke.Modules.UserDefinedTable
{

  public class EditDocument : EditControl
  {



    protected enum EditorView
    {
      ShowLinkAndControls = 2,
      ShowUpload = 1
    }



    protected Label label;
    private DocumentObject oDoc;
    protected string strDocumentFolder;
    protected FileUpload upload;





    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);

      //Init of edit control must check whether current UDT module is ready to store Document data type
      // by check ModuleContext.Settings(SettingName.DefaultFolder)
      this.strDocumentFolder = Convert.ToString(this.ModuleContext.Settings[SettingName.DocDataFolder]);

      if (string.IsNullOrEmpty(this.strDocumentFolder))
        throw new ModuleLoadException("Invalid def, Document data type must have DefaultFolder specified");

      //initialize runtime editor controls...
      //ensure enable viewstate for label
      label = new Label();
      upload = new FileUpload();
      cmdDeleteDocument = new ImageButton();
      cmdDeleteDocument.Click += new ImageClickEventHandler(cmdDeleteDocument_Click);

      this.label.EnableViewState = true;
      //disable viewstate for others
      this.upload.EnableViewState = false;
      this.cmdDeleteDocument.EnableViewState = false;

      this.cmdDeleteDocument.ImageUrl = "~/images/delete.gif";
      this.cmdDeleteDocument.OnClientClick = "javascript:return confirm('" + DotNetNuke.Services.Localization.Localization.GetString("DeleteItem") + "');";
      this.cmdDeleteDocument.ToolTip = DotNetNuke.Services.Localization.Localization.GetString("cmdDelete.Text", this.ModuleContext.PortalSettings);
      this.cmdDeleteDocument.Style["display"] = "none";

      this.Controls.Add(this.cmdDeleteDocument);
      this.Controls.Add(this.label);
      this.Controls.Add(this.upload);

      _eventMgrCtl.onRowUpdate += new UDTdataEditor.onRowUpdateEventHandler(_eventMgrCtl_onRowUpdate);
      _eventMgrCtl.onRowDelete += new UDTdataEditor.onRowDeleteEventHandler(_eventMgrCtl_onRowDelete);

    }




    protected void _deleteFile(string fileMoniker)
    {
      string strMsg = DocumentObject.DeleteDocument(ref fileMoniker);

      if (strMsg != "")
        throw new InvalidOperationException(strMsg);

      this.ViewState["value"] = "";
    }




    protected void _eventMgrCtl_onRowDelete()
    {
      //if there is a non empty value in viewstate there is file in portal that must be deleted
      if (!string.IsNullOrEmpty((string)this.ViewState["value"]))
        this._deleteFile( (string)this.ViewState["value"] );

    }




    protected void _eventMgrCtl_onRowUpdate()
    {
      System.Web.HttpContext.Current.Trace.Write("enter _eventMgrCtl_onRowUpdate");

      //if there was some file (view state is not empty) and user deleted this file (label = "")
      if (!string.IsNullOrEmpty((string)this.ViewState["value"]) && this.label.Text == "")
      {
        this._deleteFile(Convert.ToString(this.ViewState["value"]));
        System.Web.HttpContext.Current.Trace.Write("EditDocument._eventMgrCtl_onRowUpdate, _fileDelete ok");
      }

      if (this.upload.HasFile)
      {
        //this.oDoc = new DocumentObject(this.ModuleId, this.upload, this.strDocumentFolder);
        //oDoc = DocumentObject.Create(this.ModuleId, upload, strDocumentFolder, _getMaxFileSizeBytes());
        oDoc = DocumentObject.Create(this.ModuleId, upload, strDocumentFolder);

        this.ViewState["value"] = RuntimeHelpers.GetObjectValue(this.oDoc.ToMoniker());
        System.Web.HttpContext.Current.Trace.Write("EditDocument._eventMgrCtl_onRowUpdate, new file upload ok");
      }

      System.Web.HttpContext.Current.Trace.Write("_eventMgrCtl_onRowUpdate done");
    }



    /// <summary>
    /// click event on delete document imagebutton
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void cmdDeleteDocument_Click(object sender, ImageClickEventArgs e)
    {
      this.label.Text = "";
      this.updateView(EditorView.ShowUpload);
    }




    protected override bool IsNull()
    {
      //isNull = no previous value, no new value or deleted previous without set new value
      return ((this.label.Text == "") && !this.upload.HasFile);
    }





    protected override bool IsValidCustom()
    {
      int chkSize = _getMaxFileSizeBytes();

      if (chkSize > 0)
      {
        if (upload.HasFile)
          return (upload.PostedFile.ContentLength <= chkSize);

        else if (oDoc != null && label.Text != "")
          return oDoc.DocumentSize <= chkSize;

        else
          return true;


      }
      else
        return base.IsValidCustom();

    }




    protected void updateView(EditorView v)
    {
      if (v == EditorView.ShowLinkAndControls)
      {
        this.cmdDeleteDocument.Style["display"] = "";
        this.upload.Style["display"] = "none";
        this.label.Style["display"] = "";
      }
      else
      {
        this.cmdDeleteDocument.Style["display"] = "none";
        this.upload.Style["display"] = "";
        this.label.Style["display"] = "none";
      }
    }



    //protected override UDTdataEditor _eventMgrCtl { get; set; }




    protected virtual ImageButton cmdDeleteDocument
    { get; set; }





    /// <summary>
    /// Gets/ sets A string consisting out of FileID|Original FileName
    /// get is used by data table to get data into
    /// set is used by data table to show/convert value to readable form ;-)
    /// </summary>
    public override string Value
    {

      get { return Convert.ToString(this.ViewState["value"]); }

      set
      {
        if (!string.IsNullOrEmpty(value))
        {
          this.oDoc = new DocumentObject(this.ModuleId, value);
          //save value into viewstate
          this.ViewState["value"] = value;

          if (!this.Page.IsPostBack)
            this.label.Text = Convert.ToString(this.oDoc.ToLink());

          this.updateView(EditorView.ShowLinkAndControls);
        }
        else
          this.updateView(EditorView.ShowUpload);

      }
    }





    protected int _getMaxFileSizeBytes()
    {

      int tmpSize = -1;

      if (ValidationRule.ToLower().Contains("maxfilesizebytes"))
      {
        string[] tmp = ValidationRule.Split('=');

        try
        {
          tmpSize = Convert.ToInt32(tmp[1]);
        }
        catch (Exception e)
        {
          //tmpSize = 0
        }
      }

      return tmpSize;

    }



  }

}

